package com.mcxx.formulcount.gonshi;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

public class BlockServer {
    private final static Logger logger = LoggerFactory.getLogger(BlockServer.class);

    public static java.util.ArrayList<ISentence> build(java.util.ArrayList<String> arr, int p, RefObject<Integer> pos) {
        pos.argvalue = p;
        java.util.ArrayList<ISentence> rnt = new java.util.ArrayList<ISentence>();
        int ePos = 0;
        if (p >= arr.size()) {
            return rnt;
        }

        if (arr.get(p).equals("[if]")) {
            IfStentence sts = new IfStentence();
            p = sts.buildSentence(arr, p);
            rnt.add(sts);
            pos.argvalue = p - 1;
        }

        else if (arr.get(p).equals("{")) {
            p++;
            while (p < arr.size()) {
                RefObject<Integer> tempRef_ePos = new RefObject<Integer>(ePos);
                java.util.ArrayList<ISentence> sts = build(arr, p, tempRef_ePos);
                ePos = tempRef_ePos.argvalue;
                rnt.addAll(sts);
                p = ePos + 1;
                if (arr.get(p).equals("}")) {
                    pos.argvalue = p;
                    return rnt;
                }
            }
            pos.argvalue = p;
        }

        else {
            SetValueSentence sts = new SetValueSentence();
            p = sts.buildSentence(arr, p);
            pos.argvalue = p - 1;
            rnt.add(sts);
        }
        return rnt;
    }

    public static Map<String, Object> runCode(java.util.ArrayList<ISentence> sentences, Map<String, Object> vals) throws Exception {
        RuntimeContext ctx = new RuntimeContext();
        ctx.Vars = vals;
        if (null != sentences && sentences.size() > 0) {
            for (ISentence sts : sentences) {
                sts.run(ctx);
            }
        }
        return ctx.retVars;
    }
}
